package xyz.mimai.media.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * https://www.cnblogs.com/damowang/p/6226190.html
 * https://www.jianshu.com/p/8f4d754647a2
 * @ClassName Server
 * @Description 基于netty的简单的Websocket服务端
 * @Author 方丈
 * @Date 2021/2/3 17:20
 * @Version 1.0.0
 **/
public class Server {
    public static void main(String[] args) {
        //创建主线程组，只处理连接请求
        EventLoopGroup eventBossGroup = new NioEventLoopGroup(2) ;
        //创建工作线，接收主线程分发过来的任务，完成实际的工作                                                                                                                   程组
        EventLoopGroup eventWorkGroup = new NioEventLoopGroup(8) ;

        //创建一个服务器端的启动对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //设置服务器的配置
        serverBootstrap.group(eventBossGroup,eventWorkGroup)
                .channel(NioServerSocketChannel.class)
                //设置一个日志处理handler
                .handler(new LoggingHandler(LogLevel.INFO))
//                .option(ChannelOption.SO_BACKLOG,128)
//                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() {  //为eventWorkGroup相关联的管道（pipeline）设置处理器

                    //指定业务处理的自定义handler
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //添加一个空闲处理器，3秒未读或7秒未写或10秒未读写，则发送一个心跳包
                        socketChannel.pipeline().addLast(new IdleStateHandler(50,57,60, TimeUnit.SECONDS));
                        socketChannel.pipeline().addLast(new HttpServerCodec());
                        socketChannel.pipeline().addLast(new ChunkedWriteHandler());
                        //http在发送中如果数据量过大，则会分段发送，服务端接收后需要合并
                        socketChannel.pipeline().addLast(new HttpObjectAggregator(8192));
                        socketChannel.pipeline().addLast(new WebSocketServerProtocolHandler("/ws"));

                        socketChannel.pipeline().addLast(new SelfDefineWebsocketServerHandler());
                    }
                });

        System.out.println("websocket服务端初始化成功，服务中... ...");
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(88).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (InterruptedException ine){
            ine.printStackTrace();
        }finally {
            eventBossGroup.shutdownGracefully();
            eventWorkGroup.shutdownGracefully();
        }

    }


    /**
     * 自定义业务处理
     */
    public static class SelfDefineWebsocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{

        private static AtomicInteger count = new AtomicInteger(0);
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
            String content = textWebSocketFrame.text();
            System.out.println("收到消息:"+content);
            ctx.channel().writeAndFlush(new TextWebSocketFrame("收到消息，序号:"+count.incrementAndGet()+"，内容："+content ));
        }

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            super.handlerAdded(ctx);
            System.out.println(ctx.channel().id()+" handlerAdded被调用"+ctx.channel().id().asLongText());
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            super.handlerRemoved(ctx);
            System.out.println(ctx.channel().id()+" handlerRemoved被调用"+ctx.channel().id().asLongText());
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
            System.out.println(ctx.channel().id()+" exceptionCaught被调用"+ctx.channel().id().asLongText());
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            super.userEventTriggered(ctx, evt);
            if(evt instanceof IdleStateEvent){
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state()== IdleState.READER_IDLE){ // 读空闲
                    System.out.println(ctx.channel().id().asLongText()+" 读空闲");
                }else if (event.state()==IdleState.WRITER_IDLE){
                    System.out.println(ctx.channel().id().asLongText()+" 写空闲");
                }else if (event.state()==IdleState.ALL_IDLE){
                    String channelId = ctx.channel().id().asLongText();
                    ctx.channel().close();
                    System.out.println(channelId+"关闭，当前用户数");
                }
            }

        }
    }
}
